﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.BlobStoring;
using Volo.Abp.Domain.Repositories;
using Wy.JiZhangSoft.Files.Dtos;

namespace Wy.JiZhangSoft.Files
{
   
    public class FileAppService : JiZhangSoftAppService, IFileAppService
    {
        private readonly IBlobContainer _blobContainer;
        private readonly IRepository<File> _files;
        private readonly IOptions<FileOptions> _options;

        public FileAppService(IBlobContainer blobContainer,
            IRepository<File> files,
            IOptions<FileOptions> options)
        {
            this._blobContainer = blobContainer;
            this._files = files;
            this._options = options;
        }

        [Authorize]
        public async Task<Guid> SaveBytesAsync(IFormFile file)
        {
            string date = DateTime.Now.ToString("yyyy-MM-dd");
            Guid id = GuidGenerator.Create();
            // 获取文件md5
            var stream = file.OpenReadStream();
            string md5 = FileHelper.MD5Stream(stream);
            var entity = await _files.SingleOrDefaultAsync(x => x.Identification.EndsWith(md5));
            if (entity != null)
                return entity.Id;
            entity = new File(id)
            {
                Name = file.FileName,
                Identification = date + "/" + md5 + Path.GetExtension(file.FileName)
            };
            await _files.InsertAsync(entity);
            await _blobContainer.SaveAsync(entity.Identification, stream);
            return entity.Id;
        }

        [RemoteService(false)]
        public async Task<FileDownloadDto> GetBytesAsync(Guid? id)
        {
            if (!id.HasValue)
                id = Guid.Parse(_options.Value.DefaultId);
            var entity=await _files.SingleOrDefaultAsync(x => x.Id == id);
            var dto = new FileDownloadDto
            {
                Bytes = await _blobContainer.GetAllBytesOrNullAsync(entity.Identification),
                Name = entity.Name
            };
            return dto;
        }
    }
}
